package com.example.partyfee.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.partyfee.config.ExcelConfig;
import com.example.partyfee.dto.PartyMemberDTO;
import com.example.partyfee.dto.PartyMemberExcelDTO;
import com.example.partyfee.dto.PartyMemberQueryDTO;
import com.example.partyfee.entity.PartyMember;
import com.example.partyfee.excel.PartyMemberImportListener;
import com.example.partyfee.exception.BusinessException;
import com.example.partyfee.repository.PartyMemberRepository;
import com.example.partyfee.service.PartyMemberService;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class PartyMemberServiceImpl extends ServiceImpl<PartyMemberRepository, PartyMember> implements PartyMemberService {

    private final PartyMemberRepository partyMemberRepository;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void createPartyMember(PartyMemberDTO partyMemberDTO) {
        // 检查身份证号是否已存在
        if (partyMemberRepository.selectCount(new LambdaQueryWrapper<PartyMember>()
                .eq(PartyMember::getIdCard, partyMemberDTO.getIdCard())) > 0) {
            throw new BusinessException("身份证号已存在");
        }

        // 检查标识号是否已存在
        if (partyMemberRepository.selectCount(new LambdaQueryWrapper<PartyMember>()
                .eq(PartyMember::getIdentifier, partyMemberDTO.getIdentifier())) > 0) {
            throw new BusinessException("标识号已存在");
        }

        PartyMember partyMember = new PartyMember();
        BeanUtils.copyProperties(partyMemberDTO, partyMember);
        partyMemberRepository.insert(partyMember);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updatePartyMember(Long id, PartyMemberDTO partyMemberDTO) {
        PartyMember partyMember = partyMemberRepository.selectById(id);
        if (partyMember == null) {
            throw new BusinessException("党员不存在");
        }

        // 检查身份证号是否已存在
        if (!partyMember.getIdCard().equals(partyMemberDTO.getIdCard()) &&
                partyMemberRepository.selectCount(new LambdaQueryWrapper<PartyMember>()
                        .eq(PartyMember::getIdCard, partyMemberDTO.getIdCard())) > 0) {
            throw new BusinessException("身份证号已存在");
        }

        // 检查标识号是否已存在
        if (!partyMember.getIdentifier().equals(partyMemberDTO.getIdentifier()) &&
                partyMemberRepository.selectCount(new LambdaQueryWrapper<PartyMember>()
                        .eq(PartyMember::getIdentifier, partyMemberDTO.getIdentifier())) > 0) {
            throw new BusinessException("标识号已存在");
        }

        BeanUtils.copyProperties(partyMemberDTO, partyMember);
        partyMemberRepository.updateById(partyMember);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deletePartyMember(Long id) {
        if (partyMemberRepository.deleteById(id) == 0) {
            throw new BusinessException("党员不存在");
        }
    }

    @Override
    public PartyMember getPartyMember(Long id) {
        PartyMember partyMember = partyMemberRepository.selectById(id);
        if (partyMember == null) {
            throw new BusinessException("党员不存在");
        }
        return partyMember;
    }

    @Override
    public IPage<PartyMember> getPartyMemberPage(PartyMemberQueryDTO queryDTO) {
        LambdaQueryWrapper<PartyMember> wrapper = new LambdaQueryWrapper<>();
        
        // 关键词搜索
        if (StringUtils.isNotBlank(queryDTO.getKeyword())) {
            wrapper.and(w -> w
                    .like(PartyMember::getName, queryDTO.getKeyword())
                    .or()
                    .like(PartyMember::getIdCard, queryDTO.getKeyword())
                    .or()
                    .like(PartyMember::getIdentifier, queryDTO.getKeyword())
            );
        }
        
        // 班级筛选
        if (StringUtils.isNotBlank(queryDTO.getClassName())) {
            wrapper.eq(PartyMember::getClassName, queryDTO.getClassName());
        }
        
        // 职务筛选
        if (StringUtils.isNotBlank(queryDTO.getPosition())) {
            wrapper.eq(PartyMember::getPosition, queryDTO.getPosition());
        }
        
        // 职级筛选
        if (StringUtils.isNotBlank(queryDTO.getPositionLevel())) {
            wrapper.eq(PartyMember::getPositionLevel, queryDTO.getPositionLevel());
        }
        
        // 排序
        wrapper.orderByDesc(PartyMember::getCreateTime);
        
        return partyMemberRepository.selectPage(
                new Page<>(queryDTO.getCurrent(), queryDTO.getSize()),
                wrapper
        );
    }

    @Override
    public List<String> importPartyMembersFromExcel(MultipartFile file) throws IOException {
        PartyMemberImportListener listener = new PartyMemberImportListener(this);
        ExcelConfig.getReadBuilder(file.getInputStream(), PartyMemberExcelDTO.class)
                .registerReadListener(listener)
                .sheet()
                .doRead();
        return listener.getErrorMessages();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchSavePartyMembers(List<PartyMember> partyMembers) {
        if (partyMembers == null || partyMembers.isEmpty()) {
            return;
        }
        // 批量保存
        this.saveBatch(partyMembers);
    }

    @Override
    public void exportPartyMembersToExcel(PartyMemberQueryDTO queryDTO, HttpServletResponse response) throws IOException {
        // 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("党员信息", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

        // 查询数据
        queryDTO.setSize(Integer.MAX_VALUE);
        queryDTO.setCurrent(1);
        IPage<PartyMember> page = this.getPartyMemberPage(queryDTO);
        List<PartyMemberExcelDTO> excelData = page.getRecords().stream()
                .map(member -> {
                    PartyMemberExcelDTO dto = new PartyMemberExcelDTO();
                    BeanUtils.copyProperties(member, dto);
                    return dto;
                })
                .collect(Collectors.toList());

        // 导出Excel
        ExcelConfig.getWriteBuilder(response.getOutputStream(), PartyMemberExcelDTO.class)
                .sheet("党员信息")
                .doWrite(excelData);
    }
} 